#!/bin/sh
# $Revision$
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# (c) Tim Brown, 2012
# <mailto:timb@nth-dimension.org.uk>
# <http://www.nth-dimension.org.uk/> / <http://www.machine.org.uk/>
#
# Supports: Linux, AIX

if [ -z "${shadowincluded}" ]
then

shadowincluded=1

. lib/misc/file
. lib/misc/validate

shadow_list () {
	if [ "`uname`" = "AIX" ]
	then
		grep "^[A-Za-z0-9]:$" "/etc/security/passwd" | sed "s/:$//g" | while read username
		do
			printf -- "${username}\n"
		done
	else
		oldifs="${IFS}"
		IFS=":"
		egrep -v "^#|^$" "/etc/shadow" | while read username _
		do
			IFS="${oldifs}"
			printf -- "${username}\n"
			IFS=":"
		done
		IFS="${oldifs}"
	fi
}

shadow_show_hash () {
	pattern="${1}"
	[ "`validate_is_string \"${pattern}\"`" ] || false
	if [ "`uname`" = "AIX" ]
	then
		passwordflag=0
		while read line
		do
			if [ "${passwordflag}" -eq 1 ]
			then
				if [ -n "`printf -- \"${line}\" | grep \"password = \"`" ]
				then
					passwordflag=0
					printf -- "${line}\n" | while read _ _ hash
					do
						hash="`printf \"${hash}\" | sed \"s/!/\!/g\"`"
						printf -- "${hash}\n"
					done
				fi
			else
				if [ "${line}" = "${pattern}:" ]
				then
					passwordflag=1
				fi
			fi
		done <"/etc/security/passwd"
	else
		oldifs="${IFS}"
		IFS=":"
		egrep -v "^#|^$" "/etc/shadow" | while read username hash userid groupid gecos homefilename shellfilename
		do
			IFS="${oldifs}"
			if [ "${username}" = "${pattern}" ]
			then
				hash="`printf \"${hash}\" | sed \"s/!/\!/g\"`"
				printf -- "${hash}\n"
			fi
			IFS=":"
		done
		IFS="${oldifs}"
	fi
}

shadow_file_check () {
	if [ "`uname`" = "AIX" -a "`file_is_readable \"/etc/security/passwd\"`" -eq 1 ]
	then
		printf -- "1\n"
	elif [ "`file_is_readable \"/etc/shadow\"`" -eq 1 ]
	then
		printf -- "1\n"
	else
		printf -- "0\n"
	fi
}

fi
